<template>
  <q-modal v-model="modalVisible" :loading="loading" :menuBtn="!readonly && shapeAttrs.action !== 'point'"
           :submitText="submitText" btnAlign="center" header="" position="right" seamless width="350"
           @beforeClose="handleClose" @confirm="handleSubmit">
    <template v-if="shapeAttrs.action === 'line'">
      <LineAttrs ref="shapeAttrsRef" v-model:loading="loading" :readonly="readonly" :rowInfo="formInfo"></LineAttrs>
    </template>
    <template v-else-if="shapeAttrs.action === 'point'">
      <PointAttrs ref="shapeAttrsRef" v-model:loading="loading" :isBatch="isBatch" :readonly="readonly"
                  :rowInfo="formInfo" @handleClose="handleClose"></PointAttrs>
    </template>
    <template v-else-if="['text', 'area'].includes(shapeAttrs.action)">
      <AreaTextAttrs ref="shapeAttrsRef" :allRead="readonly" :readonly="readonly" :rowInfo="formInfo"
                     :type="shapeAttrs.action"></AreaTextAttrs>
    </template>
  </q-modal>
</template>

<script setup>
import { i18n } from 'boot/i18n'
import { attrsModal, exportAttrs, setAttrsModal, shapeAttrs } from 'src/views/MapCore/MapGlobal/utils/KonvaEvent'
import AreaTextAttrs from 'src/views/MapCore/MapGlobal/AttrTools/AreaTextAttrs.vue'
import LineAttrs from 'src/views/MapCore/MapGlobal/AttrTools/LineAttrs.vue'
import { computed, onUnmounted, ref, watchPostEffect } from 'vue'
import PointAttrs from 'src/views/MapCore/MapGlobal/AttrTools/PointAttrs.vue'

defineProps({ openedMap: Object, readonly: Boolean })

const formInfo = ref({})
const loading = ref(false)
const isBatch = ref(false)
const shapeAttrsRef = ref(null)
const modalVisible = ref(false)

const submitText = computed(() => {
  const { action = 'point' } = shapeAttrs.value || {}
  if (['area', 'text'].includes(action)) return i18n.t('Staging')
  if (['line'].includes(action)) return i18n.t('Submit')
  return ''
})
watchPostEffect(() => {
  const { action = 'point' } = shapeAttrs.value || {}
  if (attrsModal.value && ['line', 'point', 'area', 'text'].includes(action)) initData()
  else modalVisible.value = false
})

const initData = () => {
  const { batchSelected = [] } = exportAttrs()
  loading.value = false
  modalVisible.value = true
  isBatch.value = batchSelected.length > 1
  formInfo.value = shapeAttrs.value
}
onUnmounted(() => setAttrsModal(false))
const handleClose = () => {
  setAttrsModal(false)
  modalVisible.value = false
}
const handleSubmit = mDone => shapeAttrsRef.value && shapeAttrsRef.value.submitAjax(mDone)
</script>